<?php

class DashboardController extends BaseClass {
	
	public $title;
	public $layout = 'main';
	
	
	public function init(){
		if ( isset(Yii::app()->user->role) && Yii::app()->user->role == 2)
			$this->redirect(Yii::app()->getBaseUrl().'/admin/datacard');
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if($error = Yii::app()->errorHandler->error) {
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
				array('allow', // allow admin user to perform actions
                	'actions' => array('index', 'SettingsUpdate'),
                	'users' => $this->getAdmins(),
          		),
				array('deny', // deny other user to perform actions
						'actions' => array('index', 'SettingsUpdate'),
						'users' => array('*'),
				),
		);
	}
	/*
	 * Function to display admin dashboard
	 */
	public function actionIndex() {
		$this->title = Yii::app()->name.' :: Admin-Dashboard';
		$settings = $settings_data = $this->_loadModel();
		$contacts = Contacts::model()->findAll(array('order'=>'id desc', 'limit'=>'7'));
		$this->render('index', array('contacts'=>$contacts, 'data'=>$settings_data, 'settings'=>$settings));
	}
	/*
	 * Function to update settings from dashboard
	 */
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionSettingsUpdate()
	{
		$setting = $this->_loadModel();
		if(isset($_POST['Settings']))
		{
			$setting->attributes = $_POST['Settings'];
			$setting->created = date('Y-m-d h:i:s');
			if($setting->validate()){
				if($setting->save()) {
					return true;
				}
			}
			else return false;
		}
		exit;
	}
	

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function _loadModel()
	{
		$model=Settings::model()->find();
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}